package com.shasselclub.api.v1;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.shasselclub.api.v1.param.DaTiParam;
import com.shasselclub.api.v1.param.OpenIdParam;
import com.shasselclub.api.v1.param.ZhongJiangWriteInfo;
import com.shasselclub.api.v1.param.ZhuLiParam;
import com.shasselclub.api.v1.result.*;
import com.shasselclub.api.v1.service.GetCodeService;
import com.shasselclub.api.v1.service.RedisService;
import com.shasselclub.api.v1.service.ValidParamService;
import com.shasselclub.common.constant.ResultModel;
import com.shasselclub.common.constant.ResultStatus;
import com.shasselclub.common.utils.DateUtils;
import com.shasselclub.common.utils.IpUtils;
import com.shasselclub.common.utils.StringUtils;
import com.shasselclub.common.utils.map.GetParamToMap;
import com.shasselclub.common.utils.string.StringUtil;
import com.shasselclub.project.ask.datiRecord.domain.DatiRecord;
import com.shasselclub.project.ask.datiRecord.service.IDatiRecordService;
import com.shasselclub.project.ask.goods.domain.Goods;
import com.shasselclub.project.ask.goods.service.IGoodsService;
import com.shasselclub.project.ask.problem.domain.Answer;
import com.shasselclub.project.ask.problem.domain.Problem;
import com.shasselclub.project.ask.problem.service.IProblemService;
import com.shasselclub.project.ask.question.domain.Question;
import com.shasselclub.project.ask.question.service.IQuestionService;
import com.shasselclub.project.ask.weixinUser.service.IWeixinUserService;
import com.shasselclub.project.ask.zhuliRecord.domain.ZhuliRecord;
import com.shasselclub.project.ask.zhuliRecord.service.IZhuliRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

@Slf4j
@RestController
@RequestMapping(value = "/api/question", produces = "application/json;charset=UTF-8")
@Api(value = "问卷接口", tags  = "问卷接口",description = "3")
public class QuestionApi {
    @Autowired
    private IWeixinUserService weixinUserService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IDatiRecordService datiRecordService;
    @Autowired
    private IZhuliRecordService zhuliRecordService;
    @Autowired
    private IProblemService problemService;
    @Autowired
    private ValidParamService validParamService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private GetCodeService getCodeService;

    /**
     * 获取微信分享配置的请求
     * @param param 前台传过来的当前页面的请求地址
     * @return
     */
    @ApiOperation(notes = "获取活动信息-(打开链接或者识别二维码后页面初始化调用)" , value = "获取活动信息",response = IndexDataResult.class,position =1)
    @RequestMapping(value = "/getWxConfig",method = RequestMethod.POST)
    public Object share(@Valid OpenIdParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        IndexDataResult indexDataResult=new IndexDataResult();
        //问卷id=开始日期+结束日期
        String questionId = "";
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            //获取活动大奖
            Map<String,Object> goodQueryMap=new HashMap<>();
            List<Goods> goodsList=goodsService.selectGoodsList(goodQueryMap);
            indexDataResult.setGoodsList(goodsList);
            //查询问卷信息
            Question question= questionService.selectQuestion();
            long zhuliScore=question.getZhuliScore();
            //活动配置信息
            IndexQuestionResult questionResult=new IndexQuestionResult();
            if(!StringUtil.isNullOrEmpty(question)){
                questionResult.setQuestionTitle(question.getTitle());
                questionResult.setContent(question.getContent());
                Date startTime=question.getStartTime();
                Date endTime=question.getEndTime();
                questionResult.setStartTime(startTime);
                questionResult.setEndTime(endTime);
                questionResult.setZhuliScore(zhuliScore);
                questionId=DateUtil.format(startTime,DateUtils.YYYYMMDDHHMMSS)+DateUtil.format(endTime,DateUtils.YYYYMMDDHHMMSS);
                log.info("当前问卷id：{}",questionId);
                questionResult.setQuestionId(questionId);
                indexDataResult.setQuestion(questionResult);
                questionResult.setMusic(question.getMusic());
                long status=question.getStatus();
                 //判断活动是否在有效期内
                Date date=new Date();
                String dateNow=DateUtil.format(date, DateUtils.YYYYMMDDHHMMSS);
                String endTimeStr=DateUtil.format(endTime, DateUtils.YYYYMMDDHHMMSS);
                long betweenDay = Long.parseLong(dateNow)-Long.parseLong(endTimeStr);
                log.info("活动状态status:{}", status);
                log.info("当前时间:{}",dateNow);
                log.info("活动结束时间:{}",endTimeStr);
                log.info("betweenDay当前时间与活动结束时间间隔毫秒数:{}", betweenDay);
                if(betweenDay>0||status==0){
                    resultModel.setCode(ResultStatus.ERROR.getCode());
                    resultModel.setMessage(question.getRemark());
                    resultModel.setData(indexDataResult);
                    return resultModel;
                }
            }else{
                resultModel.setCode(ResultStatus.ERROR.getCode());
                resultModel.setMessage("获取活动配置信息出错");
                resultModel.setData(indexDataResult);
            }
            Map<String,Object> hdQueryMap=new HashMap<>();
            hdQueryMap.put("questionId", questionId);
            hdQueryMap.put("openId", param.getOpenId());
            //查询好友助力信息
            ZhuLiInfo zhuLiInfo=new ZhuLiInfo();
            List<WeiXinZhuLiInfo>  zhuLiList=new ArrayList<>();
            //查询当前排名，必须先有答题记录,才能有排行榜
            hdQueryMap.put("isNotNullMobile", "1");//只有填写了手机号之后，才算1次有效的答题
            int daTiRecordCount=datiRecordService.count(hdQueryMap);
            int rankNum=0;
            if(daTiRecordCount>0){
                 rankNum=datiRecordService.getRankNum(hdQueryMap);
                PaiHangBang paiHangBang=datiRecordService.getMyPaiHang(hdQueryMap);
                paiHangBang.setRankNum(rankNum);
                log.info("查询助力信息参数：{}",JSON.toJSONString(hdQueryMap));
                zhuLiList=zhuliRecordService.getZhuLiHeadImg(hdQueryMap);
                BeanUtil.copyProperties(paiHangBang, zhuLiInfo);
                zhuLiInfo.setZhuLiList(zhuLiList);
                indexDataResult.setZhuLiInfo(zhuLiInfo);
            }else{
                PaiHangBang paiHangBang=new PaiHangBang();
                WeiXinUserResult weiXinUserResult= weixinUserService.selectWeixinUserByMap(hdQueryMap);
                if(null!=weiXinUserResult){
                    paiHangBang.setOpenId(param.getOpenId());
                    paiHangBang.setNickName(weiXinUserResult.getNickName());
                    paiHangBang.setHeadImgUrl(weiXinUserResult.getHeadImgUrl());
                }
                paiHangBang.setRankNum(rankNum);
                log.info("查询助力信息参数：{}",JSON.toJSONString(hdQueryMap));
                BeanUtil.copyProperties(paiHangBang, zhuLiInfo);
                zhuLiInfo.setZhuLiList(zhuLiList);
                indexDataResult.setZhuLiInfo(zhuLiInfo);
            }

            //排行榜
            hdQueryMap.put("skip", 0);
            hdQueryMap.put("max", 10);
            log.info("查询排行榜参数：{}",JSON.toJSONString(hdQueryMap));
            List<PaiHangBang> paiHangBangList=datiRecordService.getPangHangPang(hdQueryMap);
            indexDataResult.setPaiHangBangList(paiHangBangList);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData(indexDataResult);
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("获取微信配置信息出错");
            resultModel.setData(indexDataResult);
        }


        return resultModel;
    }


    /**
     * 获取问卷
     * @return
     */
    @ApiOperation(notes = "获取问卷-（开始答题或者重新答题调用）" , value = "获取问卷",response = QuestionResult.class,position =2)
    @RequestMapping(value = "/get",method = RequestMethod.POST)
    public Object get(@Valid OpenIdParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        QuestionResult result=new QuestionResult();
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            /**
             * 验证微信openid是否正确
             */
            if (validParamService.validParamForOpenId(param.getOpenId(), resultModel)){
                return resultModel;
            }
            //获取当前的问卷信息
            Question question=questionService.selectQuestion();
            /**
             * 校验是否可以继续答题
             */
            //是否可以重新答题
            String openId=param.getOpenId();
            int isDaTi = getIsDaTi(question, openId).getIsDaTi();
            if(isDaTi>0){
                resultModel.setCode(ResultStatus.ERROR.getCode());
                resultModel.setMessage("本次答题次数超限，请下次活动再来参加吧");
                return resultModel;
            }
            long questionId=question.getId();
            Problem problem=new Problem();
            problem.setquestionId(questionId);
            Map<String,Object> probleQueryMap=new HashMap<>();
            probleQueryMap.put("questionId",questionId);
            List<ProblemResult> problemList=problemService.selectProblemResultList(probleQueryMap);
            result.setProblemList(problemList);
            result.setProblemNum(problemList.size());

            Date startTime=question.getStartTime();
            Date endTime=question.getEndTime();
            //获取本次活动id
            String hdId=DateUtil.format(startTime,DateUtils.YYYYMMDDHHMMSS)+DateUtil.format(endTime,DateUtils.YYYYMMDDHHMMSS);
            result.setQuestionId(hdId);
            //获取答题id
            String daTiId = datiRecordService.getDaTiId(param.getOpenId(),hdId);
            result.setDaTiId(daTiId);
            //获取题目总分
            int score=problemService.getTotalScore(probleQueryMap);
            result.setScore(score);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData(result);
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("获取微信配置信息出错");
        }
        return resultModel;
    }

    /**
     * 答题
     * @return
     */
    @ApiOperation(notes = "答题" , value = "答题",response = DaTiResult.class,position =3)
    @RequestMapping(value = "/dati",method = RequestMethod.POST)
    public Object dati(@Valid DaTiParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            /**
             * 验证问卷id是否正确
             */
            if (validParamService.validParamForQuestionId(param.getQuestionId(), resultModel)){
                return resultModel;
            }
            /**
             * 验证token
             */
            String acId=param.getAcId();
            if(!redisService.exists(acId)){
                resultModel.setCode(ResultStatus.CODE_NOTNULL_ERROR.getCode());
                resultModel.setMessage("acId不正确");
                return resultModel;
            }
            WeiXinUserResult tokenUserInfo= (WeiXinUserResult) redisService.get(acId);
            String openId=tokenUserInfo.getOpenId();
            /**
             * 验证微信openid是否正确
             */
            if (validParamService.validParamForOpenId(openId, resultModel)){
                return resultModel;
            }
            parameterMap.put("openId",openId);
            log.info("查询微信用户信息参数：{}",JSON.toJSONString(parameterMap));
            WeiXinUserResult weiXinUserResult=weixinUserService.selectWeixinUserByMap(parameterMap);
            log.info("查询微信用户信息返回结果：{}",JSON.toJSONString(weiXinUserResult));
            String id=param.getDaTiId();
            parameterMap.put("id", id);
            String questionId=param.getQuestionId();
            log.info("查询答题记录信息参数：{}", JSON.toJSONString(parameterMap));
            int count=datiRecordService.count(parameterMap);
            log.info("返回答题记录结果：{}",count);
            //保存答题内容信息
            String content="问题id:"+param.getProblemId()+",答案id："+param.getAnswerId();
            parameterMap.put("content",content);
            if(count==0){
                //新增
                parameterMap.put("nickName",weiXinUserResult.getNickName());
                parameterMap.put("headImgUrl",weiXinUserResult.getHeadImgUrl());
                log.info("答题记录新增参数：{}",JSON.toJSONString(parameterMap));
              int addCount=  datiRecordService.insertDatiRecord(parameterMap);
              log.info("答题记录新增返回结果：{}",addCount);
            }else{
                //更新
                log.info("答题记录更新参数：{}",JSON.toJSONString(parameterMap));
               int updateCount= datiRecordService.updateDatiRecord(parameterMap);
                log.info("答题记录更新返回结果：{}",updateCount);
            }

            //判断是否答题
            String answerId=param.getAnswerId();
            String problemId=param.getProblemId();
            Map<String,Object> queryMap=new HashMap<>();
            queryMap.put("answerId",answerId);
            log.info("根据问题id查询问题参数：{}", problemId);
            Problem problem=problemService.selectProblemById(problemId);
            log.info("根据问题id查询问题返回结果：{}",JSON.toJSONString(problem));
            if(StringUtil.isNullOrEmpty(problem)){
                String errMsg="答题错误，问题不存在";
                log.info(errMsg+",错误问题id：{}",problemId);
                resultModel.setMessage(errMsg);
                resultModel.setCode(ResultStatus.ERROR.getCode());
                return resultModel;
            }
            log.info("根据问题选项id查询答案信息参数：{}", JSON.toJSONString(queryMap));
            Answer answer=problemService.getAnswer(queryMap);
            log.info("根据问题选项id查询问题返回结果：{}",JSON.toJSONString(answer));
            if(StringUtil.isNullOrEmpty(answer)){
                String errMsg="答题错误，答案不存在";
                log.info(errMsg+",错误答案id：{}",answerId);
                resultModel.setMessage(errMsg);
                resultModel.setCode(ResultStatus.ERROR.getCode());
                return resultModel;
            }
            long isAnswer=answer.getIsAnswer();
            DaTiResult result=new DaTiResult();
            if(isAnswer==1){
                //答题正确
                resultModel.setCode(ResultStatus.SUCCESS.getCode());
                resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
                //增加分数和增加答对题目数量
               long addScore= problem.getScore();
               Map<String,Object> addScoreMap=new HashMap<>(2);
                addScoreMap.put("score",addScore);
                addScoreMap.put("id",id);
                log.info("答题正确，增加积分参数：{}",JSON.toJSONString(addScoreMap));
                int addCount=problemService.addScore(addScoreMap);
                log.info("答题正确，增加分数返回结果：{}",addCount);
            }else{
                //答错了，增加答错题数量
                Map<String,Object> updateAnswerWrongNumMap=new HashMap<>(2);
                updateAnswerWrongNumMap.put("id",id);
                log.info("增加答错题目数量参数：{}",JSON.toJSONString(updateAnswerWrongNumMap));
                int updateCount=problemService.updateAnswerWrongNum(updateAnswerWrongNumMap);
                log.info("增加答错题目数量返回结果：{}",updateCount);
                // 获取正确答案
                Map<String,Object> rightAnswerQueryMap=new HashMap<>(1);
                rightAnswerQueryMap.put("problemId",problemId);
                rightAnswerQueryMap.put("isAnswer","1");
                log.info("答错了，查询正确答案参数：{}",JSON.toJSONString(rightAnswerQueryMap));
                Answer rightAnswer=problemService.getAnswer(rightAnswerQueryMap);
                log.info("答错了，查询正确答案返回结果：{}",JSON.toJSONString(rightAnswer));
                if(StringUtil.isNullOrEmpty(rightAnswer)){
                    resultModel.setCode(ResultStatus.ERROR.getCode());
                    resultModel.setMessage("答错了，正确答案查询失败");
                    return resultModel;
                }
                result.setAnswer(rightAnswer.getTitle());
                result.setAnswerParse(rightAnswer.getAnswerParse());
                resultModel.setCode(ResultStatus.ERROR.getCode());
                resultModel.setMessage("哎呀,答错了");

            }
            result.setIsAnswer(isAnswer+"");
            //总得分
            int answerScore=0;
            //已答题数量
            int answerNum=0;
            Map<String,Object> scoreQueryMap=new HashMap<>();
            scoreQueryMap.put("openId",openId);
            scoreQueryMap.put("questionId", questionId);
            scoreQueryMap.put("id", id);
            int daTiRecord=datiRecordService.count(scoreQueryMap);
            if(daTiRecord>0){
                answerScore=datiRecordService.getSumScore(scoreQueryMap);
                log.info("查询当前总得分返回结果:{}",answerScore);
                //已答题目数量
                log.info("查询已答题目数参数：{}",JSON.toJSONString(scoreQueryMap));
                answerNum=datiRecordService.getAnswerNum(scoreQueryMap);
                log.info("查询已答题目数返回结果：{}",answerNum);
            }
            result.setAnswerScore(answerScore);
            result.setAnswerNum(answerNum);
            resultModel.setData(result);
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("答题出错了");
        }
        return resultModel;
    }

    @ApiOperation(notes = "填写中奖信息" , value = "填写中奖信息",response = ResultModel.class,position =4)
    @RequestMapping(value = "/write",method = RequestMethod.POST)
    public Object write(@Valid ZhongJiangWriteInfo param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            /**
             * 验证问卷id是否正确
             */
            if (validParamService.validParamForQuestionId(param.getQuestionId(), resultModel)){
                return resultModel;
            }
            String acId=param.getAcId();
            if(!redisService.exists(acId)){
                resultModel.setCode(ResultStatus.CODE_NOTNULL_ERROR.getCode());
                resultModel.setMessage("acId不正确");
                return resultModel;
            }
            WeiXinUserResult weiXinUserResult= (WeiXinUserResult) redisService.get(acId);
            parameterMap.put("openId",weiXinUserResult.getOpenId());
            //校验短信验证码是否正确
            String mobile=param.getMobile();
            String code=param.getCode();
            if(!getCodeService.validCode(mobile,code,resultModel)){
                return resultModel;
            }
            //标记答题已完成
            parameterMap.put("isComplete", "1");
            //更新
            datiRecordService.updateDatiRecord(parameterMap);
            //查询答题最高分
            log.info("查询最高分记录参数：{}",JSON.toJSONString(parameterMap));
            DatiRecord datiRecord=datiRecordService.getMaxScroreRecord(parameterMap);
            log.info("查询最高分记录返回结果：{}",JSON.toJSONString(datiRecord));
            //更新不是最高分记录
            Map<String,Object> updateNotMaxScoreRecordMap=new HashMap<>(3);
            updateNotMaxScoreRecordMap.put("questionId", param.getQuestionId());
            updateNotMaxScoreRecordMap.put("id", datiRecord.getId());
            updateNotMaxScoreRecordMap.put("openId", weiXinUserResult.getOpenId());
            datiRecordService.updateNotMaxScoreRecord(updateNotMaxScoreRecordMap);
            //更新最高分记录
            Map<String,Object> updateMaxScoreRecordMap=new HashMap<>(1);
            updateMaxScoreRecordMap.put("id",datiRecord.getId());
            datiRecordService.updateMaxScoreRecord(updateMaxScoreRecordMap);
            resultModel.setMessage("恭喜你提交成功");
            resultModel.setData("恭喜你提交成功,邀请小伙伴，助力加分拿大奖");
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("填写中奖信息出错了");
        }
        return resultModel;
    }
    @ApiOperation(notes = "助力" , value = "助力",response = ZhuLiResult.class,position =5)
    @RequestMapping(value = "/zhuli",method = RequestMethod.POST)
    public Object zhuli(@Valid ZhuLiParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            String shareOpenId=param.getShareOpenId();
            String zhuLiOpenId=param.getZhuLiOpenId();
            if(shareOpenId.equals(zhuLiOpenId)){
                resultModel.setCode(-1);
                resultModel.setMessage("不能为自己助力");
                return resultModel;
            }
            /**
             * 验证问卷id是否正确
             */
          /*  if (validParamService.validParamForQuestionId(param.getQuestionId(), resultModel)){
                return resultModel;
            }*/
            Question question=questionService.selectQuestion();
            //查询问卷信息
            if(StringUtils.isNull(question)){
                resultModel.setCode(ResultStatus.ERROR.getCode());
                resultModel.setMessage("问卷配置信息错误");
                return true;
            }
            Date startTime=question.getStartTime();
            Date endTime=question.getEndTime();
            String hdId= DateUtil.format(startTime, DateUtils.YYYYMMDDHHMMSS)+DateUtil.format(endTime,DateUtils.YYYYMMDDHHMMSS);
            parameterMap.put("questionId",hdId);
            //限制同一个用户只能给同一个人助力1次
            log.info("查询助力次数参数：{}",JSON.toJSONString(parameterMap));
            int zhuLiRecordCount=zhuliRecordService.count(parameterMap);
            log.info("查询助力次数返回结果:{}",zhuLiRecordCount);
            if(zhuLiRecordCount==0){
                //助力1次可以获得的分数
                long zhuLiScore=question.getZhuliScore();
                //保存助力结果
                ZhuliRecord zhuliRecord=new ZhuliRecord();
                zhuliRecord.setShareOpenId(shareOpenId);
                zhuliRecord.setZhuliOpenId(zhuLiOpenId);
                zhuliRecord.setScore(zhuLiScore);
                zhuliRecord.setQuestionId(hdId);
                //根据助力者openId查询助力者头像和昵称
                Map<String,Object> zhuliQueryMap=new HashMap<>(3);
                log.info("zhuLiOpenId=:{}",zhuLiOpenId);
                zhuliQueryMap.put("openId", zhuLiOpenId);
                log.info("查询分享者微信用户信息参数：{}",JSON.toJSONString(zhuliQueryMap));
                WeiXinUserResult zhuLiWeiXinResult=weixinUserService.selectWeixinUserByMap(zhuliQueryMap);
                log.info("查询分享者微信用户信息返回结果:{}",JSON.toJSONString(zhuLiWeiXinResult));
                if(!StringUtil.isNullOrEmpty(zhuLiWeiXinResult)){
                    zhuliRecord.setZhuliNickName(zhuLiWeiXinResult.getNickName());
                    zhuliRecord.setZhuliHeadImgUrl(zhuLiWeiXinResult.getHeadImgUrl());
                }
                log.info("保存助力结果参数：{}",JSON.toJSONString(zhuliRecord));
                int addCount= zhuliRecordService.insertZhuliRecord(zhuliRecord);
                log.info("保存助力结果：{}",addCount);
                //更新
                parameterMap.put("zhuLiScore",zhuLiScore);
                log.info("更新答题记录总得分，增加上本次助力的分数，参数：{}",JSON.toJSONString(parameterMap));
                int updateCount=problemService.addZhuLiScore(parameterMap);
                log.info("更新答题记录总得分，增加上本次助力的分数，结果：{}",updateCount);
            }
            //查询
            ZhuLiResult result=new ZhuLiResult();
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            Map<String,Object> weiXinUserQueryMap=new HashMap<>(1);
            weiXinUserQueryMap.put("openId", param.getShareOpenId());
            log.info("查询分享者微信用户信息参数：{}",JSON.toJSONString(weiXinUserQueryMap));
            WeiXinUserResult weiXinUserResult=weixinUserService.selectWeixinUserByMap(weiXinUserQueryMap);
            log.info("查询分享者微信用户信息返回结果:{}",JSON.toJSONString(weiXinUserResult));
            String nickName="";
            if(!StringUtil.isNullOrEmpty(weiXinUserResult)){
                nickName=weiXinUserResult.getNickName();
                result.setNickName(nickName);
            }
            resultModel.setMessage("感谢您已为"+nickName+"助力成功恭喜你获得活动资格!");
            resultModel.setData(result);
        }catch (Exception e){
            e.printStackTrace();
            log.error("助力出错了", e.toString());
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("助力出错了");
        }
        return resultModel;
    }


    /**
     * 获取微信分享配置的请求
     * @param param 前台传过来的当前页面的请求地址
     * @return
     */
    @ApiOperation(notes = "排行榜" , value = "排行榜",response = PaiHangBang.class,position =6)
    @RequestMapping(value = "/paihang",method = RequestMethod.POST)
    public Object paihang(@Valid OpenIdParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        //问卷id=开始日期+结束日期
        String questionId = "";
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            /**
             * 验证微信openid是否正确
             */
            if (validParamService.validParamForOpenId(param.getOpenId(), resultModel)){
                return resultModel;
            }
            //查询问卷信息
            Question question= questionService.selectQuestion();
            if(!StringUtil.isNullOrEmpty(question)){
                Date startTime=question.getStartTime();
                Date endTime=question.getEndTime();
                questionId=DateUtil.format(startTime,DateUtils.YYYYMMDDHHMMSS)+DateUtil.format(endTime,DateUtils.YYYYMMDDHHMMSS);
                log.info("当前问卷id：{}",questionId);
                long status=question.getStatus();
                //判断活动是否在有效期内
                Date date=new Date();
                String dateNow=DateUtil.format(date, DateUtils.YYYYMMDDHHMMSS);
                String endTimeStr=DateUtil.format(endTime, DateUtils.YYYYMMDDHHMMSS);
                long betweenDay = Long.parseLong(dateNow)-Long.parseLong(endTimeStr);
                log.info("活动状态status:{}", status);
                log.info("当前时间:{}",dateNow);
                log.info("活动结束时间:{}",endTimeStr);
                log.info("betweenDay当前时间与活动结束时间间隔毫秒数:{}", betweenDay);
                if(betweenDay>0||status==0){
                    resultModel.setCode(ResultStatus.ERROR.getCode());
                    resultModel.setMessage(question.getRemark());
                    return resultModel;
                }
            }else{
                resultModel.setCode(ResultStatus.ERROR.getCode());
                resultModel.setMessage("获取活动配置信息出错");
            }
            Map<String,Object> hdQueryMap=new HashMap<>();
            hdQueryMap.put("questionId", questionId);
            hdQueryMap.put("openId", param.getOpenId());
            //排行榜
            List<PaiHangBang> paiHangBangList=datiRecordService.getPangHangPang(hdQueryMap);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData(paiHangBangList);
        }catch (Exception e){
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("获取微信配置信息出错");
        }


        return resultModel;
    }


    /**
     * 获取是否可以答题
     * @param param 前台传过来的当前页面的请求地址
     * @return
     */
    @ApiOperation(notes = "获取是否可以答题" , value = "获取是否可以答题",response = AnswerCountResult.class,position =7)
    @RequestMapping(value = "/isAnswer",method = RequestMethod.POST)
    public Object isAnswer(@Valid OpenIdParam param, BindingResult bindingResult, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        AnswerCountResult indexDataResult=new AnswerCountResult();
        //问卷id=开始日期+结束日期
        try{
            Map<String, Object> parameterMap= GetParamToMap.getParameterMap(request);
            Map<String, Object> jsonMap= GetParamToMap.getJosnParameterMap(request);
            log.info("传递过来的参数==="+ JSON.toJSONString(parameterMap)+"ip==="+ IpUtils.getIpAddr(request));
            log.info("传递过来的jsonMap参数==="+ JSON.toJSONString(jsonMap)+"ip==="+ IpUtils.getIpAddr(request));
            if (validParamService.validParam(bindingResult, resultModel)){
                return resultModel;
            }
            //查询问卷信息
            Question question= questionService.selectQuestion();
            String openId=param.getOpenId();
            indexDataResult=getIsDaTi(question, openId);
            int isDaTi = indexDataResult.getIsDaTi();
            String hdId=getHdId(question);
            //查询最后一次答题得分
            int daTiNum=indexDataResult.getDaTiNum();
            int score=0;
            if(daTiNum>0){
                parameterMap.put("questionId",hdId);
                score=datiRecordService.getLastScore(parameterMap);
            }
            indexDataResult.setIsDaTi(isDaTi);
            indexDataResult.setScore(score);
            //获取最后一次答题id
            DatiRecord datiRecord=datiRecordService.getMaxScroreRecord(parameterMap);
            String daTiId=datiRecordService.getDaTiId(openId,hdId);
            if(!StringUtil.isNullOrEmpty(datiRecord)){
                 daTiId=datiRecord.getId()+"";
            }
            indexDataResult.setDaTiId(daTiId);
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData(indexDataResult);
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage("获取微信配置信息出错");
            resultModel.setData(indexDataResult);
        }


        return resultModel;
    }

    /**
     * 判断是否可以继续答题，0：可以答题，1：不能答题了
     * @param question
     * @param openId
     * @return
     */
    private AnswerCountResult getIsDaTi(Question question, String openId) {
        AnswerCountResult result=new AnswerCountResult();
        String hdId = getHdId(question);
        result.setQuestionId(hdId);
        Map<String,Object> hdQueryMap=new HashMap<>();
        hdQueryMap.put("questionId", hdId);
        hdQueryMap.put("openId", openId);
        //本次活动已答题次数
        int daTiCount=datiRecordService.count(hdQueryMap);
        result.setDaTiNum(daTiCount);
        log.info("本次活动已经答题次数：{}",daTiCount);
        //是否可以重新答题
        int isDaTi=0;
        hdQueryMap.put("isNotNullMobile", "1");
        log.info("查询提交答题记录数：{}",JSON.toJSONString(hdQueryMap));
        //本次活动提交次数
        int tiJiaoCount=datiRecordService.count(hdQueryMap);
        result.setTiJiaoNum(tiJiaoCount);
        log.info("本次活动已经提交次数：{}",tiJiaoCount);
        int maxDaTiNum= question.getMaxDaTiNum();
        log.info("最大可答题数量：{}",maxDaTiNum);
        //提交次数大于最大可以答题次数，限制不能再答题了
        if(daTiCount>=maxDaTiNum){
            isDaTi=1;
        }
        if(tiJiaoCount>0){
            //一旦提交之后就不能再答题了
            isDaTi=1;
        }
        result.setIsDaTi(isDaTi);
        return result;
    }

    /**
     * 获取活动问卷id
     * @param question
     * @return
     */
    private String getHdId(Question question) {
        Date startTime= question.getStartTime();
        Date endTime= question.getEndTime();
        //获取本次活动id
        return DateUtil.format(startTime, DateUtils.YYYYMMDDHHMMSS)+DateUtil.format(endTime,DateUtils.YYYYMMDDHHMMSS);
    }


}

